package com.sjyl.kaoshitong;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mikepenz.iconics.typeface.FontAwesome;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.accountswitcher.AccountHeader;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;
import com.mikepenz.materialdrawer.util.KeyboardUtil;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.activities.PayActivity;
import com.sjyl.kaoshitong.beans.ApiResponse;
import com.sjyl.kaoshitong.beans.Recontent;
import com.sjyl.kaoshitong.beans.UserInfo;
import com.sjyl.kaoshitong.fragment.DocumentMainFragment;
import com.sjyl.kaoshitong.fragment.QAMainFragment;
import com.sjyl.kaoshitong.fragment.QBMainFragment;
import com.sjyl.kaoshitong.util.APIUtils;
import com.sjyl.kaoshitong.util.OKHttpUtil;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;


public class MainActivity extends BaseActionBarActivity {
    private static final String TAG = "MainActivity";
    private Drawer.Result result = null;
    private Toolbar toolbar;
    private Fragment contentFragment;
    private Fragment documentMainFragment;
    private Fragment starFragment;
    private Fragment questionBankFragment;
    private Fragment qaCenterMainFragment;
    private IProfile profile;
    private AccountHeader.Result headerResult = null;
    private FloatingActionButton fab;
    private OkHttpClient okHttpClient;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private ProgressDialog dialog;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = getActionBarToolbar();
        // toolbar.setTitle(getString(R.string.app_name));
        // getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        preferences = getSharedPreferences("kaoshitong", MODE_PRIVATE);
        editor = preferences.edit();
        Hawk.init(this);

       // login();
        profile = new ProfileDrawerItem().withName("Shady").withEmail("slim_shady@gmail.com").withIcon(getResources().getDrawable(R.drawable.eminem));


        headerResult = new AccountHeader().withActivity(this).withHeaderBackground(R.drawable.header).addProfiles(profile).withSavedInstance(savedInstanceState)
                .build();

        result = new Drawer()
                .withActivity(this)
                .withToolbar(toolbar)
                .withAccountHeader(headerResult)
                        //.withHeader(R.layout.header)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.tab_title_document).withIcon(FontAwesome.Icon.faw_file),
                        new PrimaryDrawerItem().withName(R.string.tab_title_star).withIcon(FontAwesome.Icon.faw_star),
                        new PrimaryDrawerItem().withName(R.string.tab_title_qbank).withIcon(FontAwesome.Icon.faw_bank),
                        new PrimaryDrawerItem().withName(R.string.tab_title_qa).withIcon(FontAwesome.Icon.faw_question),
                        new PrimaryDrawerItem().withName(R.string.tab_title_center).withIcon(FontAwesome.Icon.faw_user)

                ) // add the items we want to use with our Drawer
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) {
                        if (drawerItem != null && drawerItem instanceof Nameable) {
                            getSupportActionBar().setTitle(((Nameable) drawerItem).getNameRes());
                            //ignore the DemoFragment and it's layout it's just to showcase the handle with an keyboard
                            Logger.e(TAG, "Drawer selected item " + position + "");
                            Fragment fragment = null;
                            switch (position) {
                                case 0:
                                    if (documentMainFragment == null) {
                                        documentMainFragment = DocumentMainFragment.newInstance("test");
                                    }
                                    getSupportFragmentManager().beginTransaction().replace(R.id.container, documentMainFragment).commit();
                                    break;
                                case 1:
//                                    Intent intent = new Intent(MainActivity.this, PayActivity.class);
//                                    startActivity(intent);
//                                    overridePendingTransition(R.anim.push_right_in, 0);

                                    break;
                                case 2:
                                    if (questionBankFragment == null) {
                                        questionBankFragment = QBMainFragment.newInstance("test");
                                    }
                                    getSupportFragmentManager().beginTransaction().replace(R.id.container, questionBankFragment).commit();
                                    break;
                                case 3:
                                    if (qaCenterMainFragment == null) {
                                        qaCenterMainFragment = QAMainFragment.newInstance("test");
                                    }
                                    getSupportFragmentManager().beginTransaction().replace(R.id.container, qaCenterMainFragment).commit();
                                    break;
                                case 4:
                                    if (qaCenterMainFragment == null) {
                                        qaCenterMainFragment = QAMainFragment.newInstance("test");
                                    }
                                    getSupportFragmentManager().beginTransaction().replace(R.id.container, qaCenterMainFragment).commit();
                                    break;
                                default:
                                    break;
                            }

                        }
                    }
                })
                .addStickyDrawerItems(
                        new SecondaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog).withIdentifier(10)
                )
                .withOnDrawerListener(new Drawer.OnDrawerListener() {
                    @Override
                    public void onDrawerOpened(View drawerView) {
                        KeyboardUtil.hideKeyboard(MainActivity.this);
                    }

                    @Override
                    public void onDrawerClosed(View drawerView) {

                    }
                })
                .withFireOnInitialOnClick(true)

                .withSavedInstance(savedInstanceState)
                .withActionBarDrawerToggleAnimated(true)
                .build();

        //react on the keyboard
        result.keyboardSupportEnabled(this, true);
       /* fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, FilterActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_from_right, R.anim.do_nothing);
            }
        });*/
        //fab.setBackgroundDrawable(new IconicsDrawable(this, FontAwesome.Icon.faw_filter).color(Color.WHITE).sizeDp(24));


        /*if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }*/

        //  getSupportFragmentManager().beginTransaction().add(R.id.container, DocumentMainFragment.newInstance("test")).commit();


    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
       // menu.findItem(R.id.action_search).setIcon(new IconDrawable(this, com.malinskiy.materialicons.Iconify.IconValue.md_search).colorRes(android.R.color.white).actionBarSize());
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_filter){
           /* Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);*/
        }

        if (id == R.id.action_search) {
            //go to the search fragmentActivity
            return true;
        }
        if (id == R.id.action_pay) {
            Intent intent = new Intent(MainActivity.this, PayActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            //overridePendingTransition(0,0);
        }

        return super.onOptionsItemSelected(item);
    }

    private void login(){
        dialog = new ProgressDialog(this);
        dialog.setIndeterminate(true);
        dialog.setMessage("正在登陆");
        dialog.show();
        okHttpClient = OKHttpUtil.getOkHttpClient(this);
        RequestBody body = new FormEncodingBuilder().add("funName", "doLogin").add("userName", "18659253960").add("userPass", "123456").add("phoneType", "1").build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onResponse(Response response) throws IOException {
                // Logger.json(TAG, response.body().string());
                String body = response.body().string();
                Logger.json(TAG, body);

                Type type = new TypeToken<ApiResponse<UserInfo>>() {
                }.getType();
                ApiResponse<UserInfo> apiResponse = gson.fromJson(body, type);
                Recontent<UserInfo> recontent = apiResponse.getRecontent();
                List<UserInfo> list = recontent.getRelist();
                UserInfo info = list.get(0);
                Logger.d(TAG, "=========recode:" + "  userName:" + info.getUser_name() + "  key_word   " + info.getKey_word());
                //editor.putString("key_word", info.getKey_word()).commit();
                //editor.putString("user_id", info.getPk_kst_user_list()).commit();
                Hawk.put(PreferencesKeyUtil.KEY_KEY_WORD, info.getKey_word());
                Hawk.put(PreferencesKeyUtil.KEY_USER_ID, info.getPk_kst_user_list());

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                        Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
    }

}
